const http = require('http');
const fs = require('fs');
const path = require('path');

const port = 8081;
const args = process.argv.slice(2);
const fileName = args[0] || __filename;

const server = http.createServer((req, res) => {

  fs.access(fileName, fs.constants.F_OK, (err) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end("\u6587\u4ef6 " + fileName + " \u4e0d\u5b58\u5728");
      console.error("\u6587\u4ef6 " + fileName + " \u4e0d\u5b58\u5728");
      return;
    } 


    const readStream = fs.createReadStream(fileName);
    

    readStream.on('open', () => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      readStream.pipe(res);
    });

    readStream.on('error', (err) => {
      res.writeHead(500, { 'Content-Type': 'text/plain' });
      res.end('\u8bfb\u53d6\u6587\u4ef6\u51fa\u9519');
      console.error('\u8bfb\u53d6\u6587\u4ef6\u51fa\u9519:', err);
    });
  });
});

server.listen(port, () => {
  console.log("\u670d\u52a1\u5668\u8fd0\u884c\u5728 http://localhost:" + port);
  console.log("\u5c1d\u8bd5\u8bbf\u95ee\u6587\u4ef6: " + fileName);
});

